package edu.dayu.controller;

import com.github.pagehelper.PageInfo;
import edu.dayu.pojo.Blog;
import edu.dayu.pojo.Paging;
import edu.dayu.pojo.Tag;
import edu.dayu.pojo.Type;
import edu.dayu.service.BlogService;
import edu.dayu.service.TagService;
import edu.dayu.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class BlogController {
    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private BlogService blogService;

    @GetMapping("/toBlogs")
    public String toBlogs(Blog blog,Model model){
        List<Type> types = typeService.listType();
        PageInfo<Blog> blogPageInfo = blogService.listBlog(blog);
        model.addAttribute("blogs",blogPageInfo);
        model.addAttribute("types",types);
        return "admin/blogs";
    }

    @PostMapping("/blogsSearch")
    public String blogsSearch(Blog blog,Integer typeid,Integer num,Model model){
        blog.setTypeid(typeid);
        blog.setPageNum(num);
        PageInfo<Blog> blogPageInfo = blogService.listBlog(blog);
        model.addAttribute("blogs",blogPageInfo);
        return "admin/blogs::blogsupdate";
    }

    /**
     * 初始化新增博客页面
     * @param model
     * @return
     */
    @GetMapping("/toBlogsInput")
    public String toBlogsInput(Model model){
        List<Type> types = typeService.listType();
        model.addAttribute("types",types);
        List<Tag> tags = tagService.listTag();
        model.addAttribute("tags",tags);
        return "admin/blogs-input";
    }


    /**
     * 添加新博客
    */
    @PostMapping("/saveBlogs")
    public String saveBlogs(Blog blog){
        blogService.saveBlog(blog);
        return "redirect:/toBlogs";
    }

    /**
     * 编辑博客
     */

    @GetMapping("/editBlogs")
    public String editBlogs(Blog blog ,Model model){
        Blog blog1 = blogService.getBlog(blog);
        model.addAttribute("blog",blog1);
        //初始化
        List<Type> types = typeService.listType();
        model.addAttribute("types",types);
        List<Tag> tags = tagService.listTag();
        model.addAttribute("tags",tags);
        return "admin/blogs-edit";
    }

    /**
     * 修改博客
     */

    @PostMapping("/updateBlogs")
    public String updateBlogs(Blog blog){
        blogService.updateBlog(blog);
        return "redirect:/toBlogs";
    }

    /**
     * 删除博客
     */
    @PostMapping("deleteBlog")
    @ResponseBody
    public void deleteBlog(int id){
        blogService.deleteBlog(id);
    }
}
